package com.eascs.web.p2p.member.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.p2p.common.entity.InvestorEntity;
import com.eascs.p2p.common.entity.InvestorWithdrawRecordEntity;
import com.eascs.p2p.common.security.MD5;
import com.eascs.p2p.common.service.IMsgSmsService;
import com.eascs.p2p.common.service.ISelectDataService;
import com.eascs.p2p.common.service.InvestorService;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.common.wallet.service.InvestorWalletService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.p2p.pay.service.YeePayService;

@RestController
@RequestMapping("/member/rest")
public class UserRestController extends BaseRestController {
	private final Logger logger = LoggerFactory.getLogger(UserRestController.class);

	@Reference
	InvestorService investorService;
	@Reference
	InvestorWalletService investorWalletService;
	@Reference
	ISelectDataService selectDataService;
	@Autowired
	YeePayService yeePayService;
	@Autowired
	LoginRestController loginRestController;	@Reference
	IMsgSmsService msgSmsService;
	@Value("${p2p.h5.register.msg.templateCode}")
	private String templateCode;
	
	@RequestMapping(value = "/ajax/isNameVerify", method = RequestMethod.GET)
	@ResponseBody
	public BaseRestResult<String> isNameVerify(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult=LoginRestController.isLogin(request);
		InvestorEntity investor = modelResult.getModel();
		if(investor.getIsRealname() != InvestorEntity.IS_REALNAME_YES){
			logger.info("用户没有实名认证");
			return BaseRestResult.error("用户没有实名认证");
		}
		return BaseRestResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/ajax/isWithDraw", method = RequestMethod.GET)
	@ResponseBody
	public BaseRestResult<String> isWithDraw(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult=LoginRestController.isLogin(request);
		InvestorEntity investor = modelResult.getModel();
		if(investor.getIsRealname() != InvestorEntity.IS_REALNAME_YES){
			logger.info("用户没有实名认证");
			return BaseRestResult.error("用户没有实名认证");
		}
		if(StringUtils.isBlank(investor.getTradePassword())){
			logger.info("用户没有设置交易密码");
			return BaseRestResult.error("用户没有设置交易密码");
		}
		return BaseRestResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/ajaxBindCard", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> ajaxBindCard(HttpServletRequest request,String realName,String idCardNo,String bankNo) {
		if(realName.isEmpty() || idCardNo.isEmpty() || bankNo.isEmpty()){
			logger.info("用户实名认证失败，参数不能为空,realName:{},idCardNo:{},idBankNo:{}", realName,idCardNo,bankNo);
			return BaseRestResult.error("用户实名认证失败，参数不能为空");
		}
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			logger.info("用户未登录");
			return BaseRestResult.error("用户未登录");
		}
		InvestorEntity investor = modelResult.getModel();
		if(investor.getIsRealname() == InvestorEntity.IS_REALNAME_YES){
			logger.info("用户已经通过实名认证，无需认证,investorId:{},account:{}", investor.getId(),investor.getAccount());
			return BaseRestResult.error("用户已经通过实名认证，无需认证");
		}
		ModelResult<Boolean> bindCardMR = yeePayService.bindCard(realName, idCardNo, bankNo, investor);
		if(!bindCardMR.isSuccess() || !bindCardMR.getModel()){
			logger.info("有短验绑卡请求接口调用失败，请联系管理员,realName:{},idCardNo:{},bankNo:{},investor:{}", realName, idCardNo, bankNo, investor.toString());
			return BaseRestResult.error(bindCardMR.getErrMsg());
		}
		loginRestController.resetLoginInfo(request);
		return BaseRestResult.info("true");
	}
	
	
	@RequestMapping(value = "/ajaxBindCardConfirm", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> ajaxBindCardConfirm(HttpServletRequest request,String validatecode) {
		if(validatecode.isEmpty()){
			logger.info("用户实名认证失败，参数不能为空,validatecode:{}", validatecode);
			return BaseRestResult.error("用户实名认证失败，参数不能为空");
		}
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			logger.info("用户未登录");
			return BaseRestResult.error("用户未登录");
		}
		InvestorEntity investor = modelResult.getModel();
		if(investor.getIsRealname() == InvestorEntity.IS_REALNAME_YES){
			logger.info("用户已经通过实名认证，无需认证,investorId:{},account:{}", investor.getId(),investor.getAccount());
			return BaseRestResult.error("用户已经通过实名认证，无需认证");
		}
		ModelResult<Boolean> bindCardMR = yeePayService.bindCardConfirm(validatecode, investor);
		if(!bindCardMR.isSuccess() || !bindCardMR.getModel()){
			logger.info("有短验绑卡请求短验确认接口调用失败，请联系管理员,validatecode:{},investor:{}", validatecode, investor.toString());
			return BaseRestResult.error(bindCardMR.getErrMsg());
		}
		return BaseRestResult.info("true");
	}
	
	@RequestMapping(value = "/ajaxBindCardResendsms", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> ajaxBindCardResendsms(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			logger.info("用户未登录");
			return BaseRestResult.error("用户未登录");
		}
		InvestorEntity investor = modelResult.getModel();
		if(investor.getIsRealname() == InvestorEntity.IS_REALNAME_YES){
			logger.info("用户已经通过实名认证，无需认证,investorId:{},account:{}", investor.getId(),investor.getAccount());
			return BaseRestResult.error("用户已经通过实名认证，无需认证");
		}
		ModelResult<Boolean> bindCardMR = yeePayService.bindCardResendsms(investor);
		if(!bindCardMR.isSuccess() || !bindCardMR.getModel()){
			logger.info("重新获取绑卡验证码接口调用失败，请联系管理员,investor:{}", investor.toString());
			return BaseRestResult.error(bindCardMR.getErrMsg());
		}
		return BaseRestResult.info("true");
	}
	
	@RequestMapping(value = "/unSendBindPayRequestCallBack", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> unSendBindPayRequestCallBack(HttpServletRequest request,String data, String encryptkey) {
		if (StringUtils.isBlank(data) || StringUtils.isBlank(encryptkey)) {
			logger.info("无短充值回调失败，参数为空,  data:{}, encryptkey:{}", data,encryptkey);
			return BaseRestResult.info("FAIL");
		}
		ModelResult<Boolean> modelResult = yeePayService.unSendBindPayRequestCallBack(data, encryptkey);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			return BaseRestResult.info("SUCCESS");
		}
		return BaseRestResult.info("FAIL");
	}
	
	
	@RequestMapping(value = "/withdrawByAdmin", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> withdrawByAdmin(String withdrawRecordId) {
		if (StringUtils.isBlank(withdrawRecordId)) {
			logger.info("提现失败，参数为空,  withdrawRecordId:{}", withdrawRecordId);
			return BaseRestResult.info("FAIL");
		}
		ModelResult<InvestorWithdrawRecordEntity> withdrawRecordMR=investorWalletService.queryWithdrawRecordById(withdrawRecordId);
		if (!withdrawRecordMR.isSuccess() || withdrawRecordMR.getModel() == null) {
			logger.info("提现失败，获取提款记录失败,  withdrawRecordId:{}", withdrawRecordId);
			return BaseRestResult.info("FAIL");
		}
		InvestorWithdrawRecordEntity  withdrawRecord=withdrawRecordMR.getModel();
		if (withdrawRecord.getStatus() != InvestorWithdrawRecordEntity.STATUS_SUCCESS_AUDITED) {
			logger.info("提现失败，提现状态错误，必须是审核通过,  withdrawRecordId:{}", withdrawRecordId);
			return BaseRestResult.info("FAIL");
		}
		String amount=withdrawRecord.getApplyAmount().toString();
		String investorId=withdrawRecord.getInvestorId();
		ModelResult<InvestorEntity> investorMR=investorService.queryInvestorById(investorId);
		if (!investorMR.isSuccess() || investorMR.getModel() == null) {
			logger.info("提现失败，获取用户信息失败,  investorId:{}", investorId);
			return BaseRestResult.info("FAIL");
		}
		InvestorEntity investor=investorMR.getModel();
		ModelResult<Boolean> modelResult = yeePayService.withdraw(amount, investor);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			return BaseRestResult.info("SUCCESS");
		}
		return BaseRestResult.info("FAIL");
	}
	
	@RequestMapping(value = "/withdrawCallBack", method = RequestMethod.POST)
	@ResponseBody
	public BaseRestResult<String> withdrawCallBack(HttpServletRequest request,String data, String encryptkey) {
		if (StringUtils.isBlank(data) || StringUtils.isBlank(encryptkey)) {
			logger.info("提现回调失败，参数为空,  data:{}, encryptkey:{}", data,encryptkey);
		}
		ModelResult<Boolean> modelResult = yeePayService.withdrawCallBack(data, encryptkey);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			return BaseRestResult.info("SUCCESS");
		}
		return BaseRestResult.info("FAIL");
	}
	
	/**
	 * 登录用户发送短信验证码
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/resetTranPwd/sendAuthCode", method = RequestMethod.GET)
	public BaseRestResult<?> sendAuthCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			response.sendRedirect("/member/index");
			return BaseRestResult.error("用户未登录");
		}
		InvestorEntity investorEntity =  modelResult.getModel();
		ModelResult<Boolean> msgModelResult =msgSmsService.sendAuthCode(templateCode, investorEntity.getMobile());
		if(msgModelResult.isSuccess()){
			return BaseRestResult.buildRestResult(msgModelResult.getModel());
		}
		return BaseRestResult.buildRestResult(true);
	}
	
	/**
	 * 修改交易密码
	 * @param request
	 * @param response
	 * @param erifyCode
	 * @param pw
	 * @param repeatPW
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/resetTranPwd/ajaxSubmit")
	public BaseRestResult<?> submitResetTranPwd(HttpServletRequest request, HttpServletResponse response, 
			String erifyCode, String pw, String repeatPW) throws Exception{
		ModelResult<InvestorEntity> inverstorResult = LoginRestController.isLogin(request);
		if (!inverstorResult.isSuccess() || inverstorResult.getModel() == null) {
			response.sendRedirect("/member/index");
			return BaseRestResult.error("用户未登录");
		}
		InvestorEntity investor = inverstorResult.getModel();
		if (StringUtil.isEmpty(erifyCode) || StringUtil.isEmpty(pw) || StringUtil.isEmpty(repeatPW)) {
			logger.info("修改用户交易密码失败，参数不能为空,erifyCode:{},pw:{},repeatPW:{}", erifyCode, pw, repeatPW);
			BaseRestResult.error("修改用户交易密码失败，参数不能为空");
		}
		// TODO 手机短信 确认验证码
		ModelResult<Boolean> checkResult = msgSmsService.useAuthCode(investor.getMobile(), erifyCode);
		if(checkResult.isSuccess() && checkResult.getModel()){
			if (!pw.equals(repeatPW)) {
				logger.info("用户交易密码输入不一致,pw:{},repeatPW:{}", pw, repeatPW);
				BaseRestResult.error("用户交易密码输入不一致");
			}
			InvestorEntity updateObj = new InvestorEntity();
			updateObj.setId(investor.getId());
			String password=MD5.md5Encode(pw.trim());
			updateObj.setTradePassword(password);
			ModelResult<Boolean> result = investorService.updateInvestor(updateObj);
			if (result.isSuccess()) {
				return BaseRestResult.buildRestResult(true);
			}
			return BaseRestResult.error("交易密码修改失败，请联系管理员");
		}else{
			return BaseRestResult.error("验证码校验失败");
		}
	}

}
